package uranium.gui.add;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JDialog;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;

import org.hibernate.criterion.AggregateProjection;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.view.JasperViewer;

import uranium.combo.ComboBoxAutoComplete;
import uranium.combo.MyComboClie;
import uranium.db.DBManager;
import uranium.utility.ControlloDati;

import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

public class AddOldTelGUI extends JDialog{

	private JFrame jFrame = null;  //  @jve:decl-index=0:visual-constraint="243,117"
	private JPanel jContentPane = null;
	private JPanel jPanel = null;
	private JLabel jLabel1 = null;
	private JTextField jTextField1 = null;
	private JLabel jLabel2 = null;
	private JTextField jTextField2 = null;
	private JLabel jLabel3 = null;
	private JTextField jTextField3 = null;
	private JLabel jLabel4 = null;
	private JTextField jTextField4 = null;
	private JLabel jLabel5 = null;
	private JComboBox jComboBox = null;
	//private MyComboClie jComboBox = null;
	private JButton jButton = null;
	private JButton jButton1 = null;
	private DBManager dbm = null;
	private JButton jButton2 = null;
	private JButton jButtonStampa = null;
	public AddOldTelGUI(DBManager dbm, JFrame jFrame){
		super(jFrame, false);
		this.jFrame = jFrame;
		this.dbm = dbm;
		initialize();
	}
	
	private void initialize(){
			//jFrame = new JFrame();
		this.setSize(new Dimension(440, 240));
		this.setTitle("Inserisci Telefono Usato");
		this.setPreferredSize(new Dimension(250, 188));
		this.setContentPane(getJContentPane());
		centro();
		this.setVisible(true);
	}
	
	private void centro(){
		int x = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() - this.getWidth()) / 2;
		int y = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() - this.getHeight()) / 2;
		this.setLocation(x, y);
	}

	/**
	 * This method initializes jContentPane	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getJPanel(), BorderLayout.CENTER);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			jLabel5 = new JLabel();
			jLabel5.setText("Cliente");
			jLabel5.setBounds(new Rectangle(15, 116, 49, 16));
			jLabel4 = new JLabel();
			jLabel4.setText(" Prezzo OUT");
			jLabel4.setBounds(new Rectangle(15, 92, 79, 16));
			jLabel3 = new JLabel();
			jLabel3.setText("Prezzo IN");
			jLabel3.setBounds(new Rectangle(15, 70, 63, 16));
			jLabel2 = new JLabel();
			jLabel2.setText("Modello");
			jLabel2.setBounds(new Rectangle(15, 48, 54, 16));
			jLabel1 = new JLabel();
			jLabel1.setText("IMEI ");
			jLabel1.setBounds(new Rectangle(15, 26, 36, 16));
			jPanel = new JPanel();
			jPanel.setLayout(null);
			jPanel.setPreferredSize(new Dimension(250, 166));
			jPanel.add(jLabel1, null);
			jPanel.add(getJTextField1(), null);
			jPanel.add(jLabel2, null);
			jPanel.add(getJTextField2(), null);
			jPanel.add(jLabel3, null);
			jPanel.add(getJTextField3(), null);
			jPanel.add(jLabel4, null);
			jPanel.add(getJTextField4(), null);
			jPanel.add(jLabel5, null);
			jPanel.add(getJComboBox(), null);
			jPanel.add(getJButton(), null);
			jPanel.add(getJButton1(), null);
			jPanel.add(getJButton2(), null);
			jPanel.add(getJButtonStampa(), null);
		}
		return jPanel;
	}

	/**
	 * This method initializes jTextField1	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextField1() {
		if (jTextField1 == null) {
			jTextField1 = new JTextField();
			jTextField1.setPreferredSize(new Dimension(200, 22));
			jTextField1.setBounds(new Rectangle(116, 23, 200, 22));
		}
		return jTextField1;
	}

	/**
	 * This method initializes jTextField2	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextField2() {
		if (jTextField2 == null) {
			jTextField2 = new JTextField();
			jTextField2.setPreferredSize(new Dimension(200, 22));
			jTextField2.setBounds(new Rectangle(116, 45, 200, 22));
		}
		return jTextField2;
	}

	/**
	 * This method initializes jTextField3	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextField3() {
		if (jTextField3 == null) {
			jTextField3 = new JTextField();
			jTextField3.setPreferredSize(new Dimension(200, 22));
			jTextField3.setBounds(new Rectangle(116, 67, 200, 22));
		}
		return jTextField3;
	}

	/**
	 * This method initializes jTextField4	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextField4() {
		if (jTextField4 == null) {
			jTextField4 = new JTextField();
			jTextField4.setPreferredSize(new Dimension(200, 22));
			jTextField4.setBounds(new Rectangle(116, 89, 200, 22));
		}
		return jTextField4;
	}

	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	/*private JComboBox getJComboBox() {
		if (jComboBox == null) {
			jComboBox = new MyComboClie(dbm);
			jComboBox.setPreferredSize(new Dimension(200, 22));
			jComboBox.setBounds(new Rectangle(116, 111, 200, 22));
			jComboBox.stateChange();
		}
		return jComboBox;
	}*/
	
	private JComboBox getJComboBox(){
		if (jComboBox == null){
			try{
				LinkedList lista = (LinkedList) dbm.getClienti();
	            jComboBox = new JComboBox();
	            caricaComboBox(jComboBox, lista.toArray());
	            jComboBox.setEditable(true);
	            jComboBox.setBounds(new Rectangle(116, 111, 200, 22));
	            // cmbListaPortate.addKeyListener(new MyKeyListeners());
	            //JTextComponent editor = (JTextComponent)jComboBox.getEditor().getEditorComponent();
	            //editor.addKeyListener(new MyKeyListeners());
	            new ComboBoxAutoComplete(jComboBox);

			}catch (java.lang.Throwable e){
	               // TODO: Something
			}
		}
		return jComboBox;
	}
	
	private void caricaComboBox(JComboBox combo, Object[] o){
		combo.removeAllItems();
		combo.addItem("");
		for (int i = 0; i < o.length; i++){
			combo.addItem(o[i]);
		}
	}


	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton() {
		if (jButton == null) {
			jButton = new JButton();
			jButton.setText("Nuovo");
			jButton.setBounds(new Rectangle(350, 111, 69, 26));
			jButton.addMouseListener(new java.awt.event.MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					try{
						apriAddNewClienteGUI();
					}
					catch(Exception e16){
						System.err.println(e16);
					}
				}
			});
		}
		return jButton;
	}
	
	private void apriAddNewClienteGUI(){
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				AddNewClienteGUI cerca = new AddNewClienteGUI(dbm, jFrame);
				LinkedList lista = (LinkedList) dbm.getClienti();			            
	            caricaComboBox(jComboBox, lista.toArray());
			}
		});

	}

	/**
	 * This method initializes jButton1	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setText("Inserisci");
			jButton1.setBounds(new Rectangle(150, 160, 90, 26));
			jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					try{
						boolean er = inserisci();
						if(!er)
							close();
					}
					catch(Exception e19){
						System.err.println(e19);
					}
				}
			});
		}
		return jButton1;
	}
	
	private synchronized boolean inserisci(){
		boolean error = false;
		if(jTextField1.getText().trim().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo Imei non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}
		if(jTextField2.getText().trim().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo Modello non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}
		/*if(jTextField3.getText().trim().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo PrezzoIN non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}
		if(jTextField4.getText().trim().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo PrezzoOUT DA non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}
		if(jComboBox.getSelectedItem().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo Cliente non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}*/
		if(error == false){
			String imei = jTextField1.getText();
			String modello = jTextField2.getText();
			double prezzoin = Double.valueOf(ControlloDati.aggiustaPrezzo(jTextField3.getText()));
			double prezzout = Double.parseDouble(ControlloDati.aggiustaPrezzo(jTextField4.getText()));
			//String prezzouta = ControlloDati.aggiustaPrezzo(jTextFieldA.getText());
			String cliente = (String)jComboBox.getSelectedItem();
			String insert="INSERT INTO telefoniu (imei,modello,prezzoin,prezzoout,cliente) VALUES('"+imei+"','"+modello+"','"+prezzoin+"','"+prezzout+"','"+cliente+"')";
			//stampa();
			dbm.executeQuery(insert);
			//this.dispose();
		}
		return error;
	}

	/**
	 * This method initializes jButton2	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton2() {
		if (jButton2 == null) {
			jButton2 = new JButton();
			jButton2.setBounds(new Rectangle(20, 160, 90, 26));
			jButton2.setText("Annulla");
			jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					try{
						close();
					}
					catch(Exception e33){
						e33.printStackTrace();
					}
				}
			});
		}
		return jButton2;
	}
	
	private void stampa(){
			String combo = (String)jComboBox.getSelectedItem();
			int cfind = combo.lastIndexOf("-");
			String cf = combo.substring(cfind+1);
			String query1 = "SELECT * FROM clienti WHERE id='"+cf+"'";
			String nome = "";
			String cognome = "";
			String indirizzo = "";
			String cap = "";
			String citta = "";
			try{
				ResultSet rs = dbm.executeQuery(query1);
				while(rs.next()){
					cognome = rs.getString("cognome");
					nome = rs.getString("nome");
					indirizzo = rs.getString("indirizzo");
					cap = rs.getString("cap");
					citta = rs.getString("citta");
				}
			}
			catch(Exception ed){
				ed.printStackTrace();
			}
			String imei = jTextField1.getText();
			String modello = jTextField2.getText();
			String query2 = "INSERT INTO stampa (imei,modello,cognome,nome,indirizzo,cap,citta) VALUES('"+imei+"','"+modello+"','"+cognome+"','"+nome+"','"+indirizzo+"','"+cap+"','"+citta+"')";
			dbm.executeQuery(query2);
			try{
				uranium.gui.stampa.MyJasperViewer view = new uranium.gui.stampa.MyJasperViewer(JasperFillManager.fillReport("AttRitiro.jasper", null, dbm
						.getConnessione()), false);
			System.out.println("3");
			view.setVisible(true);
			System.out.println("4");
			view.setPadre(jFrame);
			System.out.println("5");
			view.toFront();
			System.out.println("6");
			// view.setAlwaysOnTop(true);
				
				//JasperPrintManager.printReport(JasperFillManager.fillReport("AttRitiro.jasper", null, this.dbm.getConnessione()), true);
			}
			catch(JRException ef){
				ef.printStackTrace();
			}
			String query3 = "DELETE FROM stampa";
			dbm.executeQuery(query3);
	}
	
	private void close() throws SQLException{
		this.dispose();
		
	}

	/**
	 * This method initializes jButtonStampa	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonStampa() {
		if (jButtonStampa == null) {
			jButtonStampa = new JButton();
			jButtonStampa.setBounds(new Rectangle(280, 160, 135, 26));
			jButtonStampa.setText("Stampa Attestato");
			jButtonStampa.addMouseListener(new java.awt.event.MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					stampa2();
					String query3 = "DELETE FROM stampa";
					dbm.executeQuery(query3);
				}
			});
		}
		return jButtonStampa;
	}

	private void stampa2(){
		boolean error = false;
		if(jTextField1.getText().trim().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo Imei non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}
		if(jTextField2.getText().trim().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo Modello non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}
		/*if(jTextField3.getText().trim().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo PrezzoIN non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}
		if(jTextField4.getText().trim().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo PrezzoOUT DA non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}
		if(jComboBox.getSelectedItem().equals("")){
			JOptionPane.showMessageDialog(jFrame, "Campo Cliente non valido", "AVVISO", JOptionPane.INFORMATION_MESSAGE);
			error = true;
		}*/
		if(error == false){
			int scelta = JOptionPane.showConfirmDialog(jFrame, "Impostare automaticamente la data?", getTitle(), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
			String combo = (String)jComboBox.getSelectedItem();
			if(!combo.equals("")){
				int cfind = combo.lastIndexOf("-");
				String cf = combo.substring(cfind+1);
				String query1 = "SELECT * FROM clienti WHERE id='"+cf+"'";
				String nome = "";
				String cognome = "";
				String indirizzo = "";
				String cap = "";
				String citta = "";
				try{
					ResultSet rs = dbm.executeQuery(query1);
					if(rs.next()){
						cognome = rs.getString("cognome");				
						nome = rs.getString("nome");
						indirizzo = rs.getString("indirizzo");
						cap = rs.getString("cap");
						citta = rs.getString("citta");
					}		
				}
				catch(Exception ed){
					ed.printStackTrace();
				}
				String imei = jTextField1.getText();
				String modello = jTextField2.getText();
				String query2 = "INSERT INTO stampa (imei,modello,cognome,nome,indirizzo,cap,citta) VALUES('"+imei+"','"+modello+"','"+cognome+"','"+nome+"','"+indirizzo+"','"+cap+"','"+citta+"')";
				dbm.executeQuery(query2);
				try{
					if(scelta == 0){
						JasperPrint jasperPrint = JasperFillManager.fillReport("AttRitiroCD.jasper", null, dbm.getConnessione());
						JasperViewer.viewReport(jasperPrint, false);
					}
					else{
						JasperPrint jasperPrint = JasperFillManager.fillReport("AttRitiroC.jasper", null, dbm.getConnessione());
						JasperViewer.viewReport(jasperPrint, false);
					}
				} 
				catch (JRException e){
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}	
			else{
				String imei = jTextField1.getText();
				String modello = jTextField2.getText();
				String query2 = "INSERT INTO stampa (imei,modello) VALUES('"+imei+"','"+modello+"')";
				dbm.executeQuery(query2);	
				try{
					if(scelta == 0){
						JasperPrint jasperPrint = JasperFillManager.fillReport("AttRitiroSC.jasper", null, dbm.getConnessione());
						JasperViewer.viewReport(jasperPrint, false);
					}
					else{
						JasperPrint jasperPrint = JasperFillManager.fillReport("AttRitiroSCD.jasper", null, dbm.getConnessione());
						JasperViewer.viewReport(jasperPrint, false);
					}
				} 
				catch (JRException e){
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}  